﻿using System.Collections.Generic;
using System.IO;
using Core.Runtime;
using UnityEditor;
using UnityEditor.Build.Pipeline;
using UnityEditor.Build.Pipeline.Injector;
using UnityEditor.Build.Pipeline.Interfaces;
using UnityEngine;

namespace Core.Editor
{
    /// <summary>
    /// 写入增量更新数据文件
    /// </summary>
    public class WriteUpdateData : IBuildTask
    {
        [InjectContext(ContextUsage.In)]
        private IManifestParam _manifestParam;

        [InjectContext(ContextUsage.In)]
        private IBundleBuildConfigParam _configParam;

        [InjectContext(ContextUsage.In)]
        private IBundleBuildParameters _buildParam;

        public int Version => 1;

        public ReturnCode Run()
        {
            if (!NeedGenerateUpdate())
                return ReturnCode.SuccessNotRun;

            UpdateData updateData = GenerateUpdateData();
            string outputPath = GetOutputPath();

            WriteToJson(updateData, outputPath);
            Debug.Log($"成功生成更新文件：{outputPath}");

            return ReturnCode.Success;
        }

        private bool NeedGenerateUpdate()
        {
            return GameSettings.RuntimeMode == RuntimeMode.Updatable;
        }
        private UpdateData GenerateUpdateData()
        {
            return new UpdateData
            {
                ResVersion = _configParam.Config.ManifestVersion.ToString(),
                UpdateType = UpdateType.ResourceUpdate,
                UpdateStyle = UpdateStyle.Force,
                UpdateNotice = UpdateNotice.Notice,
                HotFixServerURL = "127.0.0.1",
            };
        }

        private string GetOutputPath()
        {
            string folder = Path.Combine(((BundleBuildParameters)_buildParam).OutputFolder, "Updates");
            
            Directory.CreateDirectory(folder);
            return Path.Combine(folder, $"update_v{_configParam.Config.ManifestVersion}.json");
        }

        private void WriteToJson(UpdateData data, string path)
        {
            string json = JsonUtility.ToJson(data, true);
            File.WriteAllText(path, json);
        }
    }
}
